/*
 ============================================================================
 Name		: UserDatabase.cpp
 Author	  : Lenka Litvova
 Version	 : 1.0
 Copyright   : Copyright belongs to Lenka Litvova
 Description : CUserDatabase implementation
 ============================================================================
 */

#include "UserDatabase.h"
#include "Globals.h"
#include <bautils.h> //for BaflUtils, link against: bafl.lib

CUserDatabase::CUserDatabase()
	{
	// No implementation required
	}

CUserDatabase::~CUserDatabase()
	{
	}

CUserDatabase* CUserDatabase::NewLC()
	{
	CUserDatabase* self = new (ELeave) CUserDatabase();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CUserDatabase* CUserDatabase::NewL()
	{
	CUserDatabase* self = CUserDatabase::NewLC();
	CleanupStack::Pop(); // self;
	return self;
	}

void CUserDatabase::ConstructL()
	{

	}

TBool CUserDatabase::AddNewAuthorizedUser(CFaceGraph* aFace, TDesC &aUsername)
	{
		RFs fileserver;
		User::LeaveIfError(fileserver.Connect());
		CleanupClosePushL(fileserver);
		
		TBufC<KMaxFileName> buf(KGraphs);
		TPtr pointer = buf.Des();
		pointer.Append(aUsername);
		RDebug::Print(pointer);
		
		//overenie ci pouzivatel uz neexistuje
		if (BaflUtils::FileExists(fileserver, pointer)) // file does not exist - create it
		{
			 return EFalse;
	    }
		else
		{
		//closing fileserver connection
		fileserver.Close();
		CleanupStack::PopAndDestroy(&fileserver); // destroy fs
			
		aFace->SaveGraph(pointer);
			
		return ETrue;
		}
	}

void CUserDatabase::DeleteAuthorizedUser(TDesC &aUsername)
	{
		RFs fileserver;
		User::LeaveIfError(fileserver.Connect());
		CleanupClosePushL(fileserver);
			
		TBufC<KMaxFileName> buf(KGraphs);
		TPtr pointer = buf.Des();
		pointer.Append(aUsername);
		
		BaflUtils::DeleteFile(fileserver, pointer);
		
		//closing fileserver connection
		fileserver.Close();
		CleanupStack::PopAndDestroy(&fileserver); // destroy fs
	}

TBool CUserDatabase::UserExists(TDesC &aUsername)
	{
		RFs fileserver;
		User::LeaveIfError(fileserver.Connect());
		CleanupClosePushL(fileserver);
				
		TBufC<KMaxFileName> buf(KGraphs);
		TPtr pointer = buf.Des();
		pointer.Append(aUsername);
		
		TBool result = BaflUtils::FileExists(fileserver, pointer);

		//closing fileserver connection
		fileserver.Close();
		CleanupStack::PopAndDestroy(&fileserver); // destroy fs
		
		return result;
	}
